#include <bits/stdc++.h>

using namespace std;
typedef pair <int, int> PII;
vector<int> v[4];
signed main() {
    int n, m, t = 0, no = 0; PII q = {1, 0};
    cin >> n >> m;
    v[1].resize(n + 1), v[2].resize(n + 1), v[3].resize(n + 1);
    for (int i = 1; i <= 3; ++ i) {
        for (int j = 1; j <= n; ++ j) 
            cin >> v[i][j];
        sort(v[i].begin() + 1, v[i].end());
        v[i][0] = n;
    }
    while (t = t % 3 + 1) {
        int c = 0, eld = 0, flag = 0; PII copq = q, ggg;
        aaa:
        for (int i = 1; i <= v[t][0]; ++ i) {
            if (v[t][i] > q.second) {
                if (eld != v[t][i]) {
                    eld = v[t][i];
                    c = 1;
                } else c ++;
                if (c == q.first) {
                    q = {q.first, eld};
                    for (int i = 1; i <= v[t][0] && c; ++ i) if (v[t][i] == eld) 
                    v[t].erase(v[t].begin() + i), i --, c --;
                    v[t][0] = v[t].size() - 1;
                    flag --;
                    break;
                }
            }
        }
        if (flag == 0 || flag == 2) {
            if (flag == 0) {
                flag = 2, copq = q, q = {q.first + 1, 0};
                goto aaa;
            } else {
                q = copq, no ++;
            }
        } else no = 0;
        if (no >= 2) no = 0, q = {1, 0};
        if (v[t][0] == 0) {
            cout << t;
            break;
        }
    }
    return 0;
}